package com.tieba.controller;


import com.tieba.pojo.Password;
import com.tieba.pojo.Result;
import com.tieba.pojo.User;
import com.tieba.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/users")//共同的请求路径
public class UserController {

    @Autowired
    private UserService userService;

    //查询所有用户
    @GetMapping
    public Result list(){
        log.info("查询所有用户信息");
        List<User> userList = userService.list();
        return Result.success(userList);
    }
    //根据id查询用户
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        log.info("根据id查询用户，user id:{}",id);
        User user = userService.getById(id);
        if(user == null){
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    //查询当前登录用户的信息
    @GetMapping("/me")
    public Result getCurrentUser(HttpServletRequest request){
        Integer userId = (Integer) request.getAttribute("userId");
        log.info("解析的userId:{}",userId);
        if(userId == null){
            return Result.error("Jwt的id解析为空");
        }
        User user = userService.getById(userId);
        log.info("id:{}",user.getId());
        user.setPassword("");
        return Result.success(user);
    }

    //新增用户  请求体为json格式的数据
    @PostMapping
    public Result add(@RequestBody User user){
        log.info("新增用户，user:{}",user);
        userService.add(user);
        return Result.success();
    }

    //删除用户
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        log.info("删除用户数据，ids:{}",ids);
        userService.delete(ids);
        return Result.success();
    }

    //修改/更新用户信息
    @PutMapping
    public Result update(@RequestBody User user){
        log.info("更新用户数据，user:{}",user);
        userService.update(user);
        return Result.success();
    }

    //修改密码
    @PutMapping("/password")
    public Result updatePassword(@RequestBody Password password){
        log.info("密码信息：{}",password);
        Boolean flag = userService.updatePassword(password);
        if (flag){
            return Result.success();
        }else return Result.error("信息有误");

    }

}
